import { getRouterApi } from '@/api/Router'
import { ResultType } from '@/mock/modules/Login'

export interface RouterTypeStore {
  asyncRouter: Array<RouterType> | null
  radioTitleList: Array<Omit<RouterType, 'component'>>
  menu_routes: RouterType[]
}
export const useRouterStore = defineStore('router', {
  // other options...
  state: (): RouterTypeStore => {
    return {
      asyncRouter: null,
      radioTitleList: [],
      menu_routes: []
    }
  },
  actions: {
    async SETASYNCROUTER(user: ResultType) {
      const res_router = await getRouterApi<Array<RouterType>>(user)
      this.asyncRouter = res_router.result!
    },
    ADD_RADIOTITLELIST(val: Omit<RouterType, 'component'>) {
      const isHave = this.radioTitleList.some(item => item.path === val.path)
      if (!isHave) {
        this.radioTitleList.push(val)
      }
    },
    DELETE_RADIOTITLELIST(path: string) {
      const isIndex = this.radioTitleList.findIndex(item => item.path === path)
      if (isIndex > 0) {
        this.radioTitleList.splice(isIndex, 1)
      }
    },
    CLEAR_RADIOTITLELIST() {
      this.radioTitleList = [
        { path: '/', name: 'Index', meta: { icon: 'House', title: 'home.name' } }
      ]
    }
  },
  getters: {
    keepRoutes(state): Array<string> {
      return state.radioTitleList.filter(item => !item.meta!.noKeep).map(item => item.name)
    }
  },
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'Router',
    // 修改为 sessionStorage，默认为 localStorage
    storage: window.sessionStorage,
    // 部分持久化状态的点符号路径数组，[]意味着没有状态被持久化(默认为undefined，持久化整个状态)
    paths: ['radioTitleList']
  }
})
